package com.bestbuy.controller;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.bestbuy.pojo.Account;
import com.bestbuy.service.AccountService;

@Controller
public class SignupController
{
	@Autowired
	private AccountService accountService;
	
	@RequestMapping(value = {"/signup"})
	public String RegisterAccount(Model model) {
		model.addAttribute("Page", "AccountSignup");
		return "Main";
	}

	@RequestMapping(value = {"/signup"}, method = RequestMethod.POST)
	public String RegisterAccount(
			@RequestParam(value = "username") String username,
			@RequestParam(value = "password") String password, 
			HttpSession session, Model model) 
	{
		// kiem tra thong tin dang ki
		if (username.equals("") == false && password.equals("") == false)
		{
			Account account = accountService.Register(username, password);
			if (account != null)
			{
				// dua seesion wa
				session.setAttribute("username", username);
				// tra ve trang index
				model.addAttribute("Page", "Index");
				return "Main";
			}
			else
			{
				// thong bao loi
				String error = "Tên đăng nhập hoặc mật khẩu không đúng!";
				session.setAttribute("error", error);
				// tra ve trang Signup
				model.addAttribute("Page", "AccountSignup");
				return "Main";
			}
			
		}
		return null;
		
	}

}
